import { getOtaUpgradeCommandIssuing, getOtaUpgradeList } from '@/api/tt'
import { actionDebounce } from '@/utils/mpHelper'
let tempMcuStatus = 0

export function useOtaUpgrade(haId: Ref<string> | ComputedRef<string>) {
  let wifiCount = 0
  let otemsTime = 0

  const mcuStatus = ref(0)
  const isUpgradeMR120 = ref(false)
  const isRuningUpdateMR120 = ref(false)
  const isUpdateSucMR120 = ref(false)
  const isUpdateFailMR120 = ref(false)
  const isShowContactServicePop = ref(false)
  const isCurrentUser = ref(false)
  const tempUpgradeStatus = ref(false)
  const oldVersionList = ref([
    {
      pid: '00000000000000000000000035ad0000',
      name: 'OT',
      version: '',
      serverversion: '',
      upgradeflag: false,
      fileUrl: '',
      changeLog: '',
      upgradeStatus: '', //升级状态
    },
    {
      pid: '00000000000000000000000034ad0000',
      name: 'MCU',
      version: '',
      serverversion: '',
      upgradeflag: false,
      fileUrl: '',
      changeLog: '',
      upgradeStatus: '',
    },
    {
      pid: '000000000000000000000000daac0000',
      name: 'WIFI',
      version: '',
      serverversion: '',
      upgradeflag: false,
      fileUrl: '',
      changeLog: '',
      upgradeStatus: '',
    },
  ])

  /**
   * 监听mcuSatatus变化
   * @param value
   */
  function mcuStatusChange(value: number) {
    if (value !== 1) {
      tempUpgradeStatus.value = false
    }
    if (tempMcuStatus == 0 && (value === 1 || value === 2)) {
      judgeAllOtaVersion(2)
      if (!isCurrentUser.value) {
        otemsTime = setInterval(() => {
          judgeIsUpgradeSucess(2)
        }, 30000)
      }
    } else if (value == 0 && (tempMcuStatus === 2 || tempMcuStatus === 1)) {
      judgeIsUpgradeSucess(1)
    }
    tempMcuStatus = value
  }

  /**
   * 判断所有固件是否需要升级
   * 适用于MR120升级- OT/EMS - 主MCU -WIFI模组
   * type 0首次升级 1再次升级 2再次进入页面正在升级中
   */
  async function judgeAllOtaVersion(type: number) {
    const res = await getOtaUpgradeList(haId.value)
    if (res.code === 0) {
      let list = res.data
      let isUpgradeMR120 = false
      let isShowWifiUpdate = false
      for (let i = 0; i < oldVersionList.value.length; i++) {
        for (let j = 0; j < list.length; j++) {
          if (oldVersionList.value[i].pid == list[j].pid) {
            oldVersionList.value[i].version = list[j].version
            oldVersionList.value[i].serverversion = list[j].serverversion
            oldVersionList.value[i].fileUrl = list[j].url
            oldVersionList.value[i].changeLog = list[j].changeLog
            oldVersionList.value[i].upgradeflag = list[j].upgrade
            if (list[j].upgradingVersion != '') {
              oldVersionList.value[i].upgradeStatus = 'upgrading'
            } else {
              oldVersionList.value[i].upgradeStatus = ''
            }

            if (oldVersionList.value[i].name == 'WIFI') isShowWifiUpdate = judgeIsShowWifiUpdate()
            if (
              oldVersionList.value[i].upgradeflag &&
              (oldVersionList.value[i].name != 'WIFI' || (oldVersionList.value[i].name == 'WIFI' && isShowWifiUpdate))
            ) {
              isUpgradeMR120 = true
            }
          }
        }
      }
      if (type === 0) {
        if (isUpgradeMR120) {
          showIsUpdateTip()
        }
      } else if (type === 1) {
        if (isUpgradeMR120) {
          upgradeInstructions()
        } else {
          upgradeSucess()
        }
      } else if (type === 2) {
        showUpdateTip()
      }
    }
  }

  /**
   * 确定升级-升级中
   */
  const confirmUpdate = actionDebounce({
    call: async (from?: string) => {
      upgradeInstructions(from)
    },
  })

  /**
   * 再试一次
   */
  const tryAgain = actionDebounce({
    call: async () => {
      await judgeAllOtaVersion(1)
    },
  })

  /**
   * 下发更新指令- OT/EMS - 主MCU
   * @param type
   */
  async function upgradeInstructions(from?: string) {
    if (from == 'applianceSet') {
      await judgeAllOtaVersion(0)
    }
    // return
    for (const item of oldVersionList.value) {
      if (item.upgradeStatus == '' && item.upgradeflag) {
        let params = {
          data: {
            url: item.fileUrl,
            pid: item.pid,
            version: item.serverversion,
          },
        }
        let res = await getOtaUpgradeCommandIssuing(haId.value, JSON.stringify(params))
        if (res.code == 0) {
          isCurrentUser.value = true
          tempUpgradeStatus.value = true
          showUpdateTip()
          item.upgradeStatus = 'upgrading'
          if (item.name == 'WIFI') {
            // WIFI模块下发指令后 秒查询WiFi升级状态
            setWifiStorage()
            setTimeout(() => {
              judgeIsUpgradeSucess()
            }, 49000)
          } else {
            otemsTime = setInterval(() => {
              judgeIsUpgradeSucess(2)
            }, 30000)
          }
        } else {
          upgradeFail()
        }
        break
      }
    }
  }

  /**
   * 比对版本号判断是否升级成功
   * newVersionList 新的版本
   * versionList 老版本
   * @param type
   */
  async function judgeIsUpgradeSucess(type?: number) {
    if (isUpdateFailMR120.value || isUpdateSucMR120.value) {
      return
    }
    let res = await getOtaUpgradeList(haId.value)
    if (res.code === 0) {
      let newVersionList = res.data
      let isSucess = false
      let wifiUpgrading = false
      let showFail = false
      for (let i = 0; i < newVersionList.length; i++) {
        for (let j = 0; j < oldVersionList.value.length; j++) {
          if (
            oldVersionList.value[j].upgradeStatus == 'upgrading' &&
            newVersionList[i].pid == oldVersionList.value[j].pid
          ) {
            if (oldVersionList.value[j].name != 'WIFI') {
              if (newVersionList[i].version == oldVersionList.value[j].serverversion) {
                isSucess = true
              } else {
                if (type == 1 || newVersionList[i].upgradingVersion == '') {
                  showFail = true
                  isSucess = false
                }
              }
            } else {
              wifiUpgrading = true
              if (newVersionList[i].version == oldVersionList.value[j].serverversion) {
                isSucess = true
              } else {
                if (wifiCount < 2) {
                  wifiCount++
                  setTimeout(() => {
                    judgeIsUpgradeSucess()
                  }, 5000)
                } else {
                  wifiCount++
                  isSucess = false
                }
              }
            }
          }
        }
      }
      if (isSucess) {
        upgradeSucess()
      } else {
        if ((wifiUpgrading && wifiCount == 3) || (!wifiUpgrading && showFail)) {
          upgradeFail()
        }
      }
    } else {
      upgradeFail()
    }
  }

  /**
   * 取消升级
   */
  function cancelUpdate() {
    isUpgradeMR120.value = false
  }

  /**
   * 显示是否升级弹框
   */
  function showIsUpdateTip() {
    isUpgradeMR120.value = true
    isRuningUpdateMR120.value = false
    isUpdateFailMR120.value = false
    isUpdateSucMR120.value = false
  }

  /**
   * 显示升级中弹框
   */
  function showUpdateTip() {
    isUpgradeMR120.value = false
    isRuningUpdateMR120.value = true
    isUpdateFailMR120.value = false
    isUpdateSucMR120.value = false
  }

  /**
   * 升级成功
   */
  function upgradeSucess() {
    clearInterval(otemsTime)
    isUpgradeMR120.value = false
    isRuningUpdateMR120.value = false
    isUpdateFailMR120.value = false
    isUpdateSucMR120.value = true
  }

  /**
   * 升级失败
   */
  function upgradeFail() {
    clearInterval(otemsTime)
    isUpgradeMR120.value = false
    isRuningUpdateMR120.value = false
    isUpdateFailMR120.value = true
    isUpdateSucMR120.value = false
  }

  /**
   * 隐藏所有弹框
   */
  function hideAllPop() {
    clearInterval(otemsTime)
    isUpgradeMR120.value = false
    isRuningUpdateMR120.value = false
    isUpdateFailMR120.value = false
    isUpdateSucMR120.value = false
  }

  /**
   * 显示联系客服弹框
   */
  function contactService(from?: string) {
    isShowContactServicePop.value = true
    isUpdateFailMR120.value = false
    if (from === 'applianceSet') {
      isUpgradeMR120.value = true
    }
  }

  /**
   * 隐藏联系客服弹框
   */
  function cancelCall() {
    isShowContactServicePop.value = false
  }

  /**
   * 呼叫
   */
  function confirmCall() {
    uni.makePhoneCall({
      phoneNumber: '400 820 6017',
      success: function () {
        console.log('upgradeMR120.js', 'wx.makePhoneCall', '拨打电话成功！')
      },
      fail: function () {
        console.log('upgradeMR120.js', 'wx.makePhoneCall', '拨打电话失败！')
      },
    })
  }

  /**
   * 取消成功提醒弹框
   */
  function bindSuccessTipClose() {
    isUpdateSucMR120.value = false
  }

  /**
   * 添加wifi缓存
   */
  function setWifiStorage() {
    let wifiStorageList = uni.getStorageSync('wifiUpdateList')
    let newWifiStorage = []
    let data = {
      haId: haId.value,
      updateTime: new Date().getTime(),
    }
    if (!wifiStorageList) {
      newWifiStorage.push(data)
    } else {
      let haveWifiStore = false
      wifiStorageList.forEach((item: { haId: string; updateTime: number }) => {
        if (item.haId == haId.value) {
          haveWifiStore = true
          item.updateTime = new Date().getTime()
        }
        newWifiStorage = wifiStorageList
      })
      if (!haveWifiStore) {
        newWifiStorage = wifiStorageList
        newWifiStorage.push(data)
      }
    }
    uni.setStorageSync('wifiUpdateList', newWifiStorage)
  }

  /**
   * 判断wifi是否显示是否升级的弹窗
   * 时间小于3分钟不显示是否升级弹窗
   */
  function judgeIsShowWifiUpdate() {
    let flag = true
    let wifiStorageList = uni.getStorageSync('wifiUpdateList')
    if (wifiStorageList && wifiStorageList.length > 0) {
      wifiStorageList.forEach((item: { haId: string; updateTime: number }) => {
        if (haId.value == item.haId) {
          let time = new Date().getTime() - item.updateTime
          if ((time / (1000 * 60)) % 60 < 3) {
            flag = false
          }
        }
      })
    }
    return flag
  }

  return {
    mcuStatusChange,
    judgeAllOtaVersion,
    confirmUpdate,
    tryAgain,
    upgradeInstructions,
    judgeIsUpgradeSucess,
    cancelUpdate,
    showIsUpdateTip,
    showUpdateTip,
    upgradeSucess,
    upgradeFail,
    hideAllPop,
    contactService,
    cancelCall,
    confirmCall,
    bindSuccessTipClose,
    setWifiStorage,
    judgeIsShowWifiUpdate,
    isUpgradeMR120,
    isRuningUpdateMR120,
    isUpdateSucMR120,
    isUpdateFailMR120,
    isShowContactServicePop,
    tempMcuStatus,
    isCurrentUser,
    tempUpgradeStatus,
    mcuStatus,
  }
}
